package com.example.hetong_system.controller;

import com.example.hetong_system.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayNotifyController {

    @Autowired
    private PaymentService paymentService;

    /**
     * 支付宝异步通知（唯一支付结果处理入口）
     */
    @PostMapping("/notify")
    public String handleNotify(HttpServletRequest request) {
        try {
            // 解析支付宝通知参数
            Map<String, String> params = new HashMap<>();
            request.getParameterMap().forEach((key, values) -> {
                if (values != null && values.length > 0) {
                    params.put(key, values[0]);  // 取第一个参数值
                }
            });

            // 交给Service处理
            return paymentService.handleAlipayNotify(params);
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";  // 处理失败，支付宝会重试
        }
    }
}